package com.fly.swt.progressbar;

import java.util.concurrent.TimeUnit;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * This program demonstrates BusyIndicator
 */
public class BusyIndicatorTest
{
    /**
     * The amount of time to sleep (in ms)
     */
    private static final int SLEEP_TIME = 3000;
    
    /**
     * Labels for the button
     */
    private static final String RUN = "Press to Run";
    
    private static final String IS_RUNNING = "Running...";
    
    /**
     * Runs the application
     */
    private void run()
    {
        Display display = Display.getDefault();
        Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.ON_TOP);
        shell.setText("BusyIndicator Test");
        createContents(shell);
        shell.setSize(400, 300);
        // shell.pack();
        shell.open();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        display.dispose();
    }
    
    /**
     * Create the window's contents
     * 
     * @param shell the parent shell
     */
    private void createContents(Shell shell)
    {
        shell.setLayout(new FillLayout());
        final Button button = new Button(shell, SWT.PUSH);
        button.setText(RUN);
        button.addSelectionListener(new SelectionAdapter()
        {
            @Override
            public void widgetSelected(SelectionEvent event)
            {
                // Change the button's text
                button.setText(IS_RUNNING);
                
                // Show the busy indicator
                BusyIndicator.showWhile(button.getDisplay(), () -> {
                    try
                    {
                        TimeUnit.MILLISECONDS.sleep(SLEEP_TIME);
                    }
                    catch (InterruptedException e)
                    {
                    }
                });
                
                // Thread has completed; reset the button's text
                button.setText(RUN);
            }
        });
    }
    
    /**
     * Application's entry point
     * 
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        new BusyIndicatorTest().run();
    }
}
